package com.gxa.modules.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.gxa.common.exception.ResultException;
import com.gxa.common.utils.Result;
import com.gxa.modules.pay.config.AliPayProperties;
import com.gxa.modules.pay.service.PayService;
import com.gxa.modules.sys.entity.PayOrder;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 支付宝支付
 *
 * @author shelei
 */

@Api(tags = "充值接口")
@RestController
@RequestMapping("/pay/alipay")
public class AliPayController extends AbstractAliPayApiController {
    @Autowired
    private AliPayProperties properties;

    @Autowired
    private PayService payService;

    @Override
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(properties.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                .setAppId(properties.getAppId())
                .setAliPayPublicKey(properties.getPublicKey())
//                .setAppCertPath(properties.getAppCertPath())
//                .setAliPayCertPath(properties.getAliPayCertPath())
//                .setAliPayRootCertPath(properties.getAliPayRootCertPath())
                .setCharset("UTF-8")
                .setPrivateKey(properties.getPrivateKey())
                .setServiceUrl(properties.getServerUrl())
                .setSignType("RSA2")
                // 普通公钥方式
                .build();
                // 证书模式
//                .buildByCert();
        }
        return aliPayApiConfig;
    }

    /**
     * Web支付
     */
    @ApiOperation(value = "充值")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "name",value ="购买套餐名称",dataType ="String",required = true),
            @ApiImplicitParam(paramType = "query",name = "price",value ="价格",dataType ="BigDecimal",required = true),
    })
    @RequestMapping(value = "/webPay")
    public void webPay(HttpServletResponse response, PayOrder payOrder) throws Exception {
//        //demo
        String purchaseNo = createPurchaseNo();
        payOrder.setOrderNum(purchaseNo);
        payOrder.setCreateTime(new Date());
        payOrder.setState(2); //  1：支付成功  2：待支付

        this.payService.addOrder(payOrder);

        //1、根据订单号 到数据库查询 相关的订单信息
        PayOrder order = this.payService.queyrOrder(purchaseNo);
        if(order == null){
            throw new ResultException("订单不存在");
        }

        //2、判断订单的状态 是否是待支付状态，只要不是待支付状态就说明订单失效
        if(order.getState() != 2){
            throw new ResultException("订单已失效");
        }

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //设置订单号
        model.setOutTradeNo(order.getOrderNum());
        //固定值 代号 ，数量 商品
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setTotalAmount(order.getPrice().toString()); //价格
        model.setSubject(order.getName());   //名称
        //公用回传参数，没有则无需设置
        //model.setPassbackParams("passback_params");

//        AliPayApi.tradePage(response, model, properties.getNotifyUrl(), properties.getReturnUrl());
        AliPayApi.tradePage(response, model, properties.getNotifyUrl(),"http://127.0.0.1:8080/pay/alipay/return?orderNum="+purchaseNo+"&comboId="+payOrder.getComboId()+"&userId="+ payOrder.getUserId());
    }

    /**想·
     * 支付宝异步通知接口
     */
    @PostMapping("notify_url")
    public String notifyUrl(HttpServletRequest request) throws Exception {
        //支付宝异步通知内容
        Map<String, String> params = AliPayApi.toMap(request);

        //秘钥模式
        boolean verifyResult = AlipaySignature.rsaCheckV1(params, properties.getPublicKey(), "UTF-8", "RSA2");
        //证书模式
//        boolean verifyResult = AlipaySignature.rsaCertCheckV1(params, properties.getAliPayCertPath(), "UTF-8", "RSA2");

        //验签失败
        if (!verifyResult) {
            return "failure";
        }

        //记录支付宝回调信息

        //如果支付宝返回成功更新订单状态

        //查询订单信息 根据支付宝的回调，去查询该订单的信息

        //重复通知，不再处理 如果订单状态 是已经完成
//        if(order.getStatus() == OrderStatusEnum.FINISH.getValue()){
//            return "success";
//        }


        return "success";

    }

//    public static void main(String[] args) {
//        Date date = new Date();
//        Date date1 = new Date(System.currentTimeMillis());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String format = sdf.format(date);
//        System.out.println(format);
//        System.out.println(date);
//        System.out.println(date1);
//    }
    //构建定单编号
    private static String createPurchaseNo(){
        StringBuilder sb = new StringBuilder();

        //获取当前日期
        Date date = new Date(System.currentTimeMillis());
        int year = date.getYear();
        int month = date.getMonth();
        int day = date.getDay();
        sb.append(year + month + day);

        Random random = new Random();
        int ends = random.nextInt(99);

        String format = String.format("%02d", ends);//如果不足两位，前面补0
        sb.append(format);

        return sb.toString();
    }

}
 
